<?php
/**
 * Created by PhpStorm.
 * User: Lxx<779219930@qq.com>
 * Date: 2016/4/20
 * Time: 13:47
 */

namespace app\home\controller;
use app\home\model\WechatUser;
use com\wechat\TPWechat;
use think\Config;
use think\Controller;
use app\user\controller\Index as APIIndex;
use think\Log;

/**
 * 党建主页
 */
class Index extends Controller {
    public function index(){
        return $this->fetch();
    }

    /**
     * 用户登入获取信息
     */
    public function login(){
        // 获取用户信息
        $Wechat = new TPWechat(config('party'));
        $Token = $Wechat->getOauthAccessToken();
        if($Token) {
            $user = $Wechat->getOauthUserinfo($Token['access_token'],$Token['openid']);
            if ($user){
                if ($user['privilege']){
                    $user['privilege'] = json_encode($user['privilege']);
                }
                $user['nickname'] = preg_replace('/[\x{10000}-\x{10FFFF}]/u','',$user['nickname']);
                // 添加本地数据
                $UserAPI = new APIIndex();
                $localUser = $UserAPI->checkWechatUser($Token['openid']);
                if($localUser) {
                    $UserAPI->updateWechatUser($user);
                } else {
                    $UserAPI->addWechatUser($user);
                }
                session("userId", $Token['openid']);
                //存在url则跳转，不存在则回主页
                if(session('url')){
                    $this->redirect(session('url'));
                    session('url','');
                }else{
                    $this->redirect("Index/index");
                }
            }
        } else {
            // 用户不存在通讯录，跳转到url;
            $this->redirect(session('url'));
        }
    }
}